<template>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose" width="850">
        <el-form :inline="true">
            <el-form-item label="Type" required>
                <el-select @change="meterialChange" v-model="meterialVal">
                    <el-option v-for="item in meterialList" :label="item.type" :value="item.type"
                        :key="item.type"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="Series" required>
                <el-select v-model="serieslVal" filterable @change="queryMeterial">
                    <el-option v-for="item in seriesList" :label="item" :value="item" :key="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="Specification" required>
                <el-select v-model="specificationVal">
                    <el-option v-for="item in specificationList" :label="item" :value="item" :key="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="Form" required>
                <el-select v-model="formlVal">
                    <el-option v-for="item in formList" :label="item" :value="item" :key="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="Temper" required>
                <el-select v-model="temperlVal">
                    <el-option v-for="item in temperList" :label="item" :value="item" :key="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="Thickness" required>
                <el-select v-model="thicknessVal">
                    <el-option v-for="item in thicknessList" :label="item" :value="item" :key="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="Basis" required>
                <el-select v-model="basislVal">
                    <el-option v-for="item in basisList" :label="item" :value="item" :key="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="queryMeterialByCondition">搜索材料</el-button>
            </el-form-item>
        </el-form>
        <p>选择材料属性</p>
        <div style="width: 100%;border: 1px solid #d9d9d9;border-radius: 4px;margin-top: 5px;">
            <div style="width: 100%;padding: 5px;border-bottom: 1px solid #d9d9d9;" v-for="item in chooseMeterialList"
                :key="item.name">
                <div v-if="item.data?.length > 0">
                    <div style="display: flex;justify-content: space-between;">
                        <span>材料名称：{{ item.material }} - {{ item.series }}</span>
                        <el-button type="primary" @click="deleteItem(item)">剔除</el-button>
                    </div>

                    <p>材料属性：</p>
                    <div>
                        <el-checkbox-group v-model="checkList">
                            <el-checkbox :label="el" :value="el" v-for="el in item.titles" :key="el"
                                @change="checkBoxChange($event, item, el)" />
                        </el-checkbox-group>
                    </div>
                    <p>材料数据：</p>
                    <div>
                        <el-table :data="item.data" @selection-change="handleSelectionChange($event, item)">
                            <el-table-column type="selection" width="55" />
                            <el-table-column show-overflow-tooltip prop="series" label="材料"></el-table-column>
                            <el-table-column show-overflow-tooltip prop="temper" label="热处理"></el-table-column>
                            <el-table-column show-overflow-tooltip prop="specification" label="规范"></el-table-column>
                            <el-table-column show-overflow-tooltip prop="form" label="形式"></el-table-column>
                            <el-table-column show-overflow-tooltip prop="thickness" label="毛料厚度,mm"></el-table-column>
                            <el-table-column show-overflow-tooltip prop="basis" label="基准"></el-table-column>
                            <!-- <el-table-column show-overflow-tooltip prop="" label="类型"></el-table-column> -->
                            <el-table-column show-overflow-tooltip :prop="el" :label="item.titles[index]"
                                v-for="(el, index) in item.columns"></el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button size="mini" @click="handleClose">取 消</el-button>
            <el-button size="mini" type="primary" @click="handleConfirm" :disabled="btnDisable">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
    import { v4 as uuid } from 'uuid';
    import store from "@/store";
    import { loadMeterialOptions, loadMeterialList } from '@/api/computingConfig.js'
    import { saveVeriableValue } from '@/api/computingConfig.js'
    import { refreshTableNumbers } from '@/utils/plugins/table/noteSetting'
    export default {
        name: "MaterialDialog",
        data() {
            return {
                dialogVisible: false,
                title: "选择材料",
                meterialList: [],
                seriesList: [],
                chooseMeterial: new Set(),
                chooseMeterialList: [],
                checkList: [],
                meterialVal: '',
                serieslVal: '',
                resultAttrs: new Set(),
                resultDatas: new Set(),
                resultTitles: new Set(),
                caption: null,
                specificationVal: '',
                specificationList: [],
                formlVal: '',
                formList: [],
                temperlVal: '',
                temperList: [],
                basislVal: '',
                basisList: [],
                seriesDataList: [],
                titles: [],
                columns: [],
                thicknessList: [],
                thicknessVal: '',
                btnDisable: false
            };
        },
        mounted() {
            loadMeterialOptions().then(res => {
                if (res) {
                    this.meterialList = res?.data || [];
                }
            });
        },
        methods: {
            show() {
                this.dialogVisible = true;
                this.initMaterial();
            },
            // 初始化材料数据
            initMaterial() {
                const variableContent = this.$store.state.xmleditor.allVariableContent;
                // 材料数据
                const materialData = variableContent.filter(item => {
                    return item.variableCode == 'material'
                })
                // 分类处理数据
                let typeTmpSet = new Set();
                materialData[0]?.variableContent?.data.forEach(item => {
                    typeTmpSet.add(item.type);
                });
                this.titles = materialData[0]?.variableContent?.titles.filter(item => { return item != '基准' && item != '材料' && item != '牌号' && item != '类型' && item != '规范' && item != '形式' && item != '热处理' && item != '毛料厚度,mm' });
                this.columns = materialData[0]?.variableContent?.columns.filter(item => { return item != 'basis' && item != 'code' && item != 'type' && item != 'form' && item != 'temper' && item != 'thickness' && item != 'series' && item != 'specification' });
                const typeTmpArr = [...typeTmpSet];
                typeTmpArr.forEach(async (val) => {
                    const tmpData = await materialData[0]?.variableContent?.data.filter(el => {
                        return el.type == val;
                    })
                    let seriesTmpSet = new Set();
                    tmpData.forEach(data => {
                        seriesTmpSet.add(data.series);
                    })
                    const seriesTmpArr = [...seriesTmpSet];

                    seriesTmpArr.forEach(async (series) => {
                        const tempData1 = await tmpData.filter(seriesData => {
                            return seriesData.series == series;
                        })
                        if (![...this.chooseMeterial].some(item => (item.material == val && item.series == series))) {
                            this.chooseMeterial.add({ material: val, series: series });
                        }
                        this.chooseMeterialList = [...this.chooseMeterial]
                        this.chooseMeterialList.forEach(item => {
                            if (item.material === val && item.series === series) {
                                item.titles = this.titles;
                                item.data = tempData1;
                                item.columns = this.columns
                                this.$forceUpdate();
                            }
                        })
                    })
                })
            },
            // 选择材料
            meterialChange(val) {
                let filterSeries = [];
                filterSeries = this.meterialList.filter(item => {
                    return item.type == val
                })
                this.seriesList = filterSeries[0]?.series || [];
                this.serieslVal = '';
                this.formList = []
                this.temperList = []
                this.basisList = []
                this.specificationList = [];
                this.specificationVal = ""
                this.formlVal = ""
                this.basislVal = ""
                this.temperlVal = ""
                this.thicknessVal = ""
                this.thicknessList = []
            },
            queryMeterial() {
                // 查询数据
                this.formList = []
                this.temperList = []
                this.basisList = []
                this.specificationList = [];
                this.specificationVal = ""
                this.formlVal = ""
                this.basislVal = ""
                this.temperlVal = ""
                this.thicknessVal = ""
                this.thicknessList = []
                loadMeterialList({ series: this.serieslVal, type: this.meterialVal }).then(async (res) => {
                    if (res) {
                        this.seriesDataList = res?.data.data;
                        this.titles = res?.data.titles.filter(item => { return item != '基准' && item != '材料' && item != '牌号' && item != '类型' && item != '规范' && item != '形式' && item != '热处理' && item != '毛料厚度,mm' });
                        this.columns = res?.data.columns.filter(item => { return item != 'basis' && item != 'code' && item != 'type' && item != 'form' && item != 'temper' && item != 'thickness' && item != 'series' && item != 'specification' });
                        let specificationSet = new Set();
                        let formSet = new Set()
                        let temperSet = new Set();
                        let basisSet = new Set();
                        let thicknessSet = new Set();
                        await this.seriesDataList.forEach(item => {
                            specificationSet.add(item.specification)
                            formSet.add(item.form)
                            temperSet.add(item.temper)
                            basisSet.add(item.basis)
                            thicknessSet.add(item.thickness)
                        })
                        this.specificationList = [...specificationSet]
                        this.formList = [...formSet]
                        this.temperList = [...temperSet]
                        this.basisList = [...basisSet]
                        this.thicknessList = [...thicknessSet]
                    }
                })
            },
            // 条件查询材料数据
            async queryMeterialByCondition() {
                if (!this.meterialVal) {
                    return this.$message.warning('请选择材料！')
                }
                if (!this.serieslVal) {
                    return this.$message.warning('请选择series！')
                }
                if (!this.specificationVal) {
                    return this.$message.warning('请选择specification！')
                }
                if (!this.formlVal) {
                    return this.$message.warning('请选择form！')
                }
                if (!this.temperlVal) {
                    return this.$message.warning('请选择temper！')
                }
                if (!this.thicknessVal) {
                    return this.$message.warning('请选择thickness！')
                }
                if (!this.basislVal) {
                    return this.$message.warning('请选择basis！')
                }
                let filterData = [];
                if (this.specificationVal) {
                    filterData = await this.seriesDataList.filter(item => {
                        return item.specification == this.specificationVal
                    })
                }
                if (this.formlVal) {
                    filterData = await filterData.filter(item => {
                        return item.form == this.formlVal
                    })
                }
                if (this.thicknessVal) {
                    filterData = await filterData.filter(item => {
                        return item.thickness == this.thicknessVal
                    })
                }
                if (this.temperlVal) {
                    filterData = await filterData.filter(item => {
                        return item.temper == this.temperlVal
                    })
                }
                if (this.basislVal) {
                    filterData = await filterData.filter(item => {
                        return item.basis == this.basislVal
                    })
                }
                if (filterData.length > 0) {
                    if (![...this.chooseMeterial].some(item => (item.material == this.meterialVal && item.series == this.serieslVal))) {
                        this.chooseMeterial.add({ material: this.meterialVal, series: this.serieslVal });
                    }
                    this.chooseMeterialList = [...this.chooseMeterial]
                    this.chooseMeterialList.forEach(item => {
                        if (item.material === this.meterialVal && item.series === this.serieslVal) {
                            item.titles = this.titles;
                            //数据去重
                            let newData = [];
                            if (item.data?.length > 0) {
                                filterData?.forEach(el => {
                                    let hasel = false;
                                    item.data?.forEach(data => {
                                        if (el.code == data.code) {
                                            hasel = true;
                                        }
                                    })
                                    if (!hasel) {
                                        newData.push(el);
                                    }
                                })
                                item.data = [...item.data, ...newData];
                            } else {
                                item.data = filterData;
                            }
                            item.columns = this.columns
                            this.$forceUpdate();
                        }
                    })
                }
            },
            //删除属性
            deleteItem(data) {
                this.chooseMeterialList = this.chooseMeterialList.filter(el => {
                    return !(el.material === data.material && el.series === data.series)
                })
                this.resultDatas = new Set(Array.from(this.resultDatas).filter(item => { return !(item.material === data.material && item.series === data.series) }))
                this.resultAttrs = new Set(Array.from(this.resultAttrs).filter(item => { return !(item.material === data.material && item.series === data.series) }))
                this.resultTitles = new Set(Array.from(this.resultTitles).filter(item => { return !(item.material === data.material && item.series === data.series) }))
                this.$forceUpdate();
            },
            async handleConfirm() {
                this.btnDisable = true;
                //先删除表
                const doc = tinymce.activeEditor.getDoc();
                let materialTables = doc.querySelectorAll('table');
                for (let tableIndex = 0; tableIndex < materialTables.length; tableIndex++) {
                    if (materialTables[tableIndex].dataset?.variableId?.includes('0000')) {
                        materialTables[tableIndex].remove();
                    }
                }
                //组装table数据
                let tableTitles = [];
                Array.from(this.resultTitles).forEach(item => {
                    tableTitles = [...tableTitles, ...item.datas]
                })
                let tableDatas = [];
                Array.from(this.resultDatas).forEach(item => {
                    tableDatas = [...tableDatas, ...item.datas]
                })
                let tableAttrs = [];
                Array.from(this.resultAttrs).forEach(item => {
                    tableAttrs = [...tableAttrs, ...item.datas]
                })
                const tableId = this.$store.state.xmleditor.variableTableDataId;

                if (!tableDatas.length) {
                    return this.$message.warning('请选择数据！')
                }
                const totalNum = tableDatas?.length || 0;
                // 数据分类
                let groupData = await this.countMeterial(tableDatas);
                let contentValue = Object.keys(groupData).length || 0;
                // 排序
                let sortArr = [];
                await Object.keys(groupData).forEach(key => {
                    sortArr.push({ key: key, count: groupData[key].length })
                })
                sortArr.sort((a, b) => b.count - a.count);
                console.log("排序")

                let tableDataNew = [];
                await sortArr.forEach(item => {
                    tableDataNew = [...tableDataNew, ...groupData[item.key]];
                })
                console.log(tableDataNew)
                if (tableId?.dataId) {
                    const doc = tinymce.activeEditor.getDoc();
                    const nodes = doc.querySelector(`[data-id="${tableId?.dataId}"]`)
                    const tableChildren = nodes.childNodes;
                    const staticTitles = [{ name: "材料", value: "series" }, { name: "热处理", value: "temper" }, { name: "规范", value: "specification" }, { name: "形式", value: "form" }, { name: "毛料厚度,mm", value: "thickness" }, { name: "基准", value: "basis" }]
                    tableChildren.forEach(el => {
                        if (el.nodeName == 'CAPTION' || el.tagName == 'CAPTION') {
                            this.caption = el;
                        }
                        // 表头设置
                        if (el.nodeName == 'THEAD' || el.tagName == 'THEAD') {
                            let tr = '';
                            let th = '';
                            th = `<th colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${staticTitles[0].name}​</p>
	                    </th>`
                            tr += th;
                            const dataLength = totalNum > 6 ? 6 : totalNum
                            for (let i = 0; i < dataLength; i++) {
                                let th = '';
                                const data = tableDataNew[i];
                                if (data) {
                                    th = `<th colspan="1" rowspan="1" data-id="${uuid()}">
                                    <p data-type="paragraph" data-lang="zh">${data[staticTitles[0].value]}​</p>
                                </th>`
                                    tr += th;
                                }
                            }
                            tr = `<tr data-id="${uuid()}">${tr}</tr>`
                            el.innerHTML = tr
                        }
                        // 数据设置
                        if (el.nodeName == 'TBODY' || el.tagName == 'TBODY') {
                            let tbody = '';
                            if (tableDataNew.length > 0) {
                                staticTitles.forEach((item, index) => {
                                    if (index > 0) {
                                        let tr = '';
                                        let td = '';
                                        td = `<td colspan="1" rowspan="1" data-id="${uuid()}">
                                        <p data-type="paragraph" data-lang="zh">${item.name}​</p>
                                    </td>`
                                        tr += td;
                                        const dataLength = totalNum > 6 ? 6 : totalNum
                                        for (let i = 0; i < dataLength; i++) {
                                            let th = '';
                                            const data = tableDataNew[i];
                                            if (data) {
                                                let th = '';
                                                th = `<td colspan="1" rowspan="1" data-id="${uuid()}">
                                                <p data-type="paragraph" data-lang="zh">${data[item.value]}​</p>
                                            </td>`
                                                tr += th;
                                            }
                                        }
                                        tbody += `<tr data-id="${uuid()}">${tr}</tr>`
                                    }

                                })

                                tableAttrs.forEach((tdData, arrIndex) => {
                                    let tr = '';
                                    let td = '';
                                    td = `<td colspan="1" rowspan="1" data-id="${uuid()}">
                                <p data-type="paragraph" data-lang="zh">${tableTitles[arrIndex]}​</p>
                            </td>`
                                    tr += td;
                                    const dataLength = totalNum > 6 ? 6 : totalNum
                                    for (let i = 0; i < dataLength; i++) {
                                        let th = '';
                                        const data = tableDataNew[i];
                                        if (data) {
                                            let th = '';
                                            th = `<td colspan="1" rowspan="1" data-id="${uuid()}">
                                            <p data-type="paragraph" data-lang="zh">${data[tdData] || ''}​</p>
                                        </td>`
                                            tr += th;
                                        }
                                    }
                                    tbody += `<tr data-id="${uuid()}">${tr}</tr>`
                                })
                            }
                            el.innerHTML = tbody
                        }
                    })
                    this.mergeTableCells(nodes, 1);
                    if (totalNum > 6) {
                        const tableNumbers = Math.ceil(totalNum / 6);
                        for (let i = 1; i < tableNumbers; i++) {
                            if (i == 1) {
                                const currentNode = tinymce.activeEditor.selection.select(nodes);
                                tinymce.activeEditor.selection.collapse(false);
                            } else {
                                const subNodes = doc.querySelector(`[data-variable-id="0000${i - 1}"]`)
                                const currentNode = tinymce.activeEditor.selection.select(subNodes);
                                tinymce.activeEditor.selection.collapse(false);
                            }
                            const subTableData = tableDataNew.slice(i * 6, (i + 1) * 6);
                            let tr = '';
                            let th = '';
                            th = `<th colspan="1" rowspan="1" data-id="${uuid()}">
		                        <p data-type="paragraph" data-lang="zh">${staticTitles[0].name}​</p>
	                        </th>`
                            tr += th;
                            for (let i = 0; i < subTableData.length; i++) {
                                let th = '';
                                const data = subTableData[i];
                                if (data) {
                                    th = `<th colspan="1" rowspan="1" data-id="${uuid()}">
                                    <p data-type="paragraph" data-lang="zh">${data[staticTitles[0].value]}​</p>
                                </th>`
                                    tr += th;
                                }
                            }
                            tr = `<tr data-id="${uuid()}">${tr}</tr>`;
                            let tbody = '';
                            staticTitles.forEach((item, index) => {
                                if (index > 0) {
                                    let trBody = '';
                                    let tdBody = '';
                                    tdBody = `<td colspan="1" rowspan="1" data-id="${uuid()}">
                                        <p data-type="paragraph" data-lang="zh">${item.name}​</p>
                                    </td>`
                                    trBody += tdBody;
                                    for (let i = 0; i < subTableData.length; i++) {
                                        let th = '';
                                        const data = subTableData[i];
                                        if (data) {
                                            let th = '';
                                            th = `<td colspan="1" rowspan="1" data-id="${uuid()}">
                                                <p data-type="paragraph" data-lang="zh">${data[item.value]}​</p>
                                            </td>`
                                            trBody += th;
                                        }
                                    }
                                    tbody += `<tr data-id="${uuid()}">${trBody}</tr>`
                                }

                            })

                            tableAttrs.forEach((tdData, index) => {
                                let tr = '';
                                let td = '';
                                td = `<td colspan="1" rowspan="1" data-id="${uuid()}">
                                <p data-type="paragraph" data-lang="zh">${tableTitles[index]}​</p>
                            </td>`
                                tr += td;
                                for (let i = 0; i < subTableData.length; i++) {
                                    let th = '';
                                    const data = subTableData[i];
                                    if (data) {
                                        let th = '';
                                        th = `<td colspan="1" rowspan="1" data-id="${uuid()}">
                                            <p data-type="paragraph" data-lang="zh">${data[tdData] || ''}​</p>
                                        </td>`
                                        tr += th;
                                    }
                                }
                                tbody += `<tr data-id="${uuid()}">${tr}</tr>`
                            })
                            // tinymce.activeEditor.insertContent(`<p data-type="paragraph" data-block-id="${uuid()}" data-id="${uuid()}">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>`)
                            tinymce.activeEditor.insertContent(
                                `<table border="1" class="data-content-table" data-type="table" data-variable-id='0000${i}' data-block-id="${uuid()}" data-id="${uuid()}" style="border-collapse: collapse; width: 98.0521%;" data-mce-selected="1">
                                    <caption data-id="${uuid()}" class="table_caption zh">
                                        <p class="caption zh" >材料性能表</p>
                                    </caption>
                                <thead>
                                    ${tr}
                                </thead>
                                    <tbody>
                                        ${tbody}
                                    </tbody>
                                </table>`
                            );
                            store.commit("xmleditor/UPDATE_DOC_STRUCTURE");
                            const tablenodes = doc.querySelector(`[data-variable-id="0000${i}"]`);
                            this.mergeTableCells(tablenodes, 1);
                        }
                    }
                }
                refreshTableNumbers(tinymce.activeEditor);
                //更新标注引用
                // 替换表注
                const tableIndexMap = [
                    { tableName: 'provision', tableIndexName: 'provision.tableNumber' },
                    { tableName: 'material', tableIndexName: 'material.tableNumber' },
                    { tableName: 'fastener', tableIndexName: 'fastener.tableNumber' },
                    { tableName: 'msSummary', tableIndexName: 'msSummary.tableNumber' },
                    { tableName: 'loadCaseStatistics', tableIndexName: 'loadCaseStatistics.tableNumber' },
                    { tableName: 'algoResultTable', tableIndexName: 'algoResultTable.tableNumber' },
                ]
                const variableList = this.$store.state.xmleditor.allVariableContent;
                const allVariables = this.$store.state.xmleditor.allVariables;
                tableIndexMap.forEach(async (item) => {
                    const tableVariableInfo = await variableList.filter(el => {
                        return el.variableCode == item.tableName;
                    })
                    const tableIndexVariableInfo = await variableList.filter(el => {
                        return el.variableCode == item.tableIndexName;
                    })
                    //查找table的dom
                    const tableDom = doc.querySelector(`[data-variable-id="${tableVariableInfo[0]?.id}"]`)
                    const tableIndexDom = doc.querySelector(`[data-variable-id="${tableIndexVariableInfo[0]?.id}"]`)
                    if (tableIndexDom) {
                        if (item.tableIndexName == 'material.tableNumber') {
                            let meterialIndexStr = [];
                            const allTableNode = doc.querySelectorAll(`[data-type="table"]`);
                            const meterialTableNode = [];
                            await allTableNode.forEach(item => {
                                if (item?.dataset?.variableId?.includes('0000')) {
                                    meterialTableNode.push(item);
                                }
                            })
                            meterialTableNode.forEach(tableNode => {
                                meterialIndexStr.push(tableNode?.getAttribute('data-number'));
                            })
                            if (meterialIndexStr.length > 0) {
                                tableIndexDom.innerText = `${tableDom?.getAttribute('data-number')},${meterialIndexStr.toString()}`;
                            } else {
                                tableIndexDom.innerText = tableDom?.getAttribute('data-number');
                            }
                        } else {
                            tableIndexDom.innerText = tableDom?.getAttribute('data-number');
                        }
                    }
                    // 算例结果表标注替换
                    if (item.tableName == 'algoResultTable') {
                        const algoResultTableIndexStr = await allVariables.filter(el => {
                            return el.variableCode == 'algoResultTable.tableNumber';
                        })
                        const algoResultTableName = await allVariables.filter(el => {
                            return el.variableCode == 'algoResultTable';
                        })
                        const algoTableDom = doc.querySelectorAll(`[data-variable-id="${algoResultTableIndexStr[0]?.id}"]`)
                        const algoTableIndexDom = doc.querySelectorAll(`[data-variable-id="${algoResultTableName[0]?.id}"]`)
                        algoTableIndexDom.forEach((item, index) => {
                            const algoTableNumber = item?.getAttribute('data-number');
                            algoTableDom[index].innerText = algoTableNumber
                        })
                    }
                })
                // 保存变量值
                const variableContent = {
                    columns: tableAttrs,
                    titles: tableTitles,
                    data: tableDatas
                }
                const formData = new FormData();
                formData.append("docNo", this.$store.state.xmleditor.docInfo.docNo);
                formData.append("id", Number.parseInt(tableId?.variableId));
                formData.append("variableContent", JSON.stringify(variableContent));
                // saveVeriableValue(formData);
                // 设置材料总数
                this.allVariables = this.$store.state.xmleditor.allVariableContent;
                const meterialCount = this.allVariables.filter(el => {
                    return el.variableCode == 'material.count'
                })
                const meterialCountNode = doc.querySelector(`[data-variable-id="${meterialCount[0]?.id}"]`);
                meterialCountNode.innerText = contentValue;
                const formData1 = new FormData();
                formData1.append("docNo", this.$store.state.xmleditor.docInfo.docNo);
                formData1.append("id", Number.parseInt(meterialCount[0]?.id));
                formData1.append("variableContent", contentValue);
                saveVeriableValue(formData1);
                this.btnDisable = false;
                this.dialogVisible = false;
            },
            // 统计材料总数
            async countMeterial(data) {
                let groupData = await data.reduce((acc, obj) => {
                    const key = `${obj.series}_${obj.temper}_${obj.type}`;
                    acc[key] = acc[key] || [];
                    acc[key].push(obj);
                    return acc;
                }, {});
                return groupData;
            },
            // 合并单元格
            mergeTableCells(table, columnIndex) {
                const rows = table.rows;
                for (let i = 0; i < rows.length; i++) {
                    let lastValue = null;
                    let colspan = 1;
                    let cells = rows[i].cells;
                    const cellsLength = cells.length;
                    if (i < 4) {
                        for (let j = 0; j < cellsLength; j++) {
                            const value = cells[j]?.innerText;
                            if (value) {
                                if (lastValue == value) {
                                    colspan++;
                                    cells[j - colspan + 1].colSpan = colspan
                                    cells[j].innerText = ""
                                    cells[j]?.remove();

                                } else {
                                    lastValue = value;
                                    colspan = 1;
                                }
                            }else{
                                colspan++;
                                cells[j - colspan + 1].colSpan = colspan;
                                cells[cellsLength-j+1]?.remove();
                            }
                        }
                    }

                }
                this.$forceUpdate();
            },
            handleSelectionChange(val, data) {
                if (val) {
                    let hasData = false;
                    this.resultDatas.forEach(item => {
                        if (item.material == data.material && item.series == data.series) {
                            item.datas = [...val]
                            hasData = true;
                        }
                    })
                    if (!hasData) {
                        this.resultDatas.add({ material: data.material, series: data.series, datas: [...val] });
                    }
                }
            },
            handleClose() {
                this.dialogVisible = false;
            },
            checkBoxChange(val, data, el) {
                let hasData1 = false;
                let hasData2 = false;
                const index = data.titles.findIndex(item => item == el)
                const column = data.columns[index];
                if (val) {
                    this.resultTitles.forEach(item => {
                        if (item.material == data.material && item.series == data.series) {
                            if (!item?.datas.includes(el)) {
                                item.datas.push(el);
                            }
                            hasData1 = true;
                        }
                    })
                    if (!hasData1) {
                        this.resultTitles.add({ material: data.material, series: data.series, datas: [el] });
                    }
                    this.resultAttrs.forEach(item => {
                        if (item.material == data.material && item.series == data.series) {
                            if (!item?.datas.includes(column)) {
                                item.datas.push(column);
                            }
                            hasData2 = true;
                        }
                    })
                    if (!hasData2) {
                        this.resultAttrs.add({ material: data.material, series: data.series, datas: [column] });
                    }
                } else {
                    this.resultTitles.forEach(item => {
                        if (item.material == data.material && item.series == data.series) {
                            if (item?.datas.includes(el)) {
                                item.datas = item.datas.filter(p => p != el);
                            }
                        }
                    })
                    this.resultAttrs.forEach(item => {
                        if (item.material == data.material && item.series == data.series) {
                            if (item?.datas.includes(column)) {
                                item.datas = item.datas.filter(p => p != column);
                            }
                        }
                    })
                }
            },
        },
    };
</script>

<style scoped>
    .variable-class {
        font-style: italic;
        text-decoration: underline;
        color: blue;
    }

    .replace-img {
        text-align: center;
    }

    .ins-table {
        width: 100%;
    }

    ::v-deep .el-dialog {
        min-width: 800px;
    }

    ::v-deep .el-dialog__body {
        padding-top: 0;
        padding-bottom: 10px;
    }
</style>